<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/6/10
 * Time: 11:42
 */
namespace App\Services;

use App\Model\GroupModel;
use App\Model\GroupMsgModel;
use App\Model\GroupSysMsgModel;
use App\Model\MsgModel;
use App\Model\UserModel;
use App\Services\ReponseCodeService;
use App\Services\HelpService;
use App\Logic\GroupLogic;
use App\Model\UserGroupModel;
use App\Logic\UserGroupLogic;
use EasySwoole\ORM\DbManager;
use EasySwoole\EasySwoole\Config;

class GroupService
{
    /**
     *修改群管理员
     */
    public function groupMemberSetting($param,$userInfo){
        try{
            //开启事务
            DbManager::getInstance()->startTransaction();
            $appUserIdsArr = explode(',',$param['app_user_ids']);
            foreach ($appUserIdsArr as  $appUserId){
                #用户不存在，直接失败
                $memberUserInfo = UserModel::create()->get(['app_user_id'=>$appUserId,'app_id'=>$userInfo['app_id']]);
                if(empty($memberUserInfo)){
                    return ReponseCodeService::CODE_FAILE;
                }
                #成员不存在，直接失败
                if(!UserGroupModel::create()->get(['user_id'=>$memberUserInfo['id'],'group_id'=>$param['group_id']])){
                    return ReponseCodeService::CODE_FAILE;
                }
                #修改角色
                UserGroupModel::create()->update(['role'=>$param['role'],'updated_at'=>HelpService::msectimeToStr(HelpService::msectime())],['user_id'=>$memberUserInfo['id'],'group_id'=>$param['group_id']]);
            }
        } catch(\Throwable  $e){
            //回滚事务
            DbManager::getInstance()->rollback();
            return ['code'=>ReponseCodeService::CODE_FAILE];
        } finally {
            //提交事务
            DbManager::getInstance()->commit();
        }
        #系统消息入库
        try{
            $extra['app_user_ids'] = $appUserIdsArr;
            $extra['role'] = $param['role'];

            $sysData['user_id'] = 0;
            $sysData['to_id'] = $param['group_id'];
            $sysData['sub_type'] = MsgModel::SUB_TYPE_GOUP_SYS_MSG;
            $sysData['app_id'] = $userInfo['app_id'];
            $sysData['msg'] = '';
            $sysData['extra'] = json_encode($extra);
            $sysData['nonce'] = HelpService::msectime().HelpService::createNonce(6);
            $sysData['type'] = PrivateMsgService::MSG_TYPE_GROUP_MEMBER_INFO_CHANGE;
            $sysData['created_at'] = HelpService::msectimeToStr(HelpService::msectime());
            $sysData['updated_at'] = HelpService::msectimeToStr(HelpService::msectime());
            $msgId = GroupSysMsgModel::create()->data($sysData)->save();
        }catch(\Throwable $t){
            return ['code'=>ReponseCodeService::CODE_FAILE];
        }
        return ['code'=>ReponseCodeService::CODE_OK,'msg_id'=>$msgId];
    }

    /**根据字符串，获取临时名字
     * @param $tempName
     * @return bool|string
     */
    public function createTempName($sourcestr, $cutlength=30){
        $sourcestr = trim($sourcestr,'、');
        $returnstr = '';
        $i = 0;
        $n = 0;
        $str_length = strlen ( $sourcestr ); //字符串的字节数
        while ( ($n < $cutlength) and ($i <= $str_length) ) {
            $temp_str = substr ( $sourcestr, $i, 1 );
            $ascnum = Ord ( $temp_str ); //得到字符串中第$i位字符的ascii码
            if ($ascnum >= 224) {//如果ASCII位高与224，
                $returnstr = $returnstr . substr ( $sourcestr, $i, 3 ); //根据UTF-8编码规范，将3个连续的字符计为单个字符
                $i = $i + 3; //实际Byte计为3
                $n ++; //字串长度计1
            } elseif ($ascnum >= 192){ //如果ASCII位高与192，
                $returnstr = $returnstr . substr ( $sourcestr, $i, 2 ); //根据UTF-8编码规范，将2个连续的字符计为单个字符
                $i = $i + 2; //实际Byte计为2
                $n ++; //字串长度计1
            } elseif ($ascnum >= 65 && $ascnum <= 90) {//如果是大写字母，
                $returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
                $i = $i + 1; //实际的Byte数仍计1个
                $n ++; //但考虑整体美观，大写字母计成一个高位字符
            }elseif ($ascnum >= 97 && $ascnum <= 122) {
                $returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
                $i = $i + 1; //实际的Byte数仍计1个
                $n ++; //但考虑整体美观，大写字母计成一个高位字符
            } else {//其他情况下，半角标点符号，
                $returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
                $i = $i + 1;
                $n = $n + 0.5;
            }
        }
        return $returnstr;
    }

    /**
     * 最近联系的客服群
     */
    public function recentUsers($param,$serviceUserId){
        try{
            #获取客服群
            $page = $param['page'];          // 当前页码
            $limit = $param['limit'];        // 每页多少条数据
            $model = GroupModel::create()
                ->where(['service_user_id'=>$serviceUserId])
                ->limit($limit * ($page - 1), $limit)
                ->withTotalCount();
           // 列表数据
            $list = $model->all(null);
            $result = $model->lastQueryResult();
            // 总条数
            $total = $result->getTotalCount();
            if(!empty($list )){
                #获取最后一条消息
                $host = Config::getInstance()->getConf('APP.FILE_DOMAIN');
                foreach ($list as $k=>$group){
                    #绑定发送人信息
                    $owner = UserModel::create()->get(['id'=>$group]);
                    $group['client']['nickname']  = $owner['nickname'];
                    $group['client']['head']  = $owner['head'];
                    $group['lastMeaasge'] = null;
                    $meaasge = GroupMsgModel::create()->get(['id'=>$group['id']]);
                    if(empty($meaasge)){
                        continue;
                    }
                    $userInfo = UserModel::create()->get(['id'=>$meaasge['user_id']]);
                    $data = array(
                        'group_id' =>$group['id'],
                        'content'=>$meaasge['msg'],
                        'type'=>$meaasge['type'],
                        'extra'=>json_decode($meaasge['extra'],true),
                        'app_user_id'=>$userInfo['app_user_id'],
                        'nickname'=>$userInfo['nickname'],
                        'head'=>$userInfo['head'],
                    );

                    #文件处理
                    switch ($data['type']){
                        case PrivateMsgService::MSG_TYPE_IMAGE://图片,后续等比缩放
                            $data['extra']['url'] = "{$host}/{$data['content']}";
                            $thumbWidth = 480;
                            $thumbHeight = (int)($thumbWidth/ $data['extra']['width']* $data['extra']['height']);
                            $data['extra']['thumb_url'] = "{$host}{$data['content']}?/3/w/{$thumbWidth}/h/{$thumbHeight}";

                            $data['extra']['thumbHeight'] = $thumbHeight;
                            $data['extra']['thumbWidth'] = $thumbWidth;
                            break;
                        case PrivateMsgService::MSG_TYPE_VOICE:
                            $data['extra']['voice_url'] = "{$host}/{$data['content']}";
                            break;
                        case PrivateMsgService::MSG_TYPE_VIDEO://视频,后续等比缩放
                            $thumbWidth = 480;
                            $thumbHeight = 360;
                            $data['extra']['cover_url'] = "{$host}{$data['content']}?vframe/jpg/offset/0/w/{$thumbWidth}/h/{$thumbHeight}";
                            $data['extra']['thumbHeight'] = $thumbHeight;
                            $data['extra']['thumbWidth'] = $thumbWidth;
                            $data['extra']['video_url'] = "{$host}{$data['content']}";
                            break;
                    }
                    $data['service_msg'] = true;
                    $messageArr = array(
                        'data'=>json_encode($data),
                        'action'=>'groupChat',
                        'nonce'=>$meaasge['nonce'],
                        'time'=> HelpService::strDateToMsectime($meaasge['created_at']),
                        'msg_id'=>$meaasge['id'],
                        'group_id' =>$group['id'],
                    );
                    $group['lastMeaasge'] = $messageArr;
                }
            }
            $returnData['page'] = $page;
            $returnData['limit'] = $limit;
            $returnData['list'] = $list;
            $returnData['total'] = $total;
            return $returnData;
         }catch(\Throwable $t){
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }

    /**获取群详情
     * @param $param
     * @param $userInfo
     */
    public function groupDetail($param,$userInfo){
        try{
            $condition['id']     = $param['extra']['group_id'];
            $condition['status'] = GroupModel::STATUS_NORMAL;
            $groupInfo =  GroupModel::create()->get($condition);
            if(empty( $groupInfo)){
                return ReponseCodeService::CODE_USER_NOT_AUTH;
            }
            $groupInfo['created_at'] = HelpService::strDateToMsectime( $groupInfo['created_at']);
            $groupInfo['updated_at'] = HelpService::strDateToMsectime( $groupInfo['updated_at']);

            #群角色
            $userGroup = UserGroupModel::create()->get(['user_id'=>$userInfo['id'],'group_id'=>$param['extra']['group_id'],'status'=>UserGroupModel::STATUS_NORMAL]);
            if(empty( $userGroup)){
                return ReponseCodeService::CODE_NOT_GROUP_MEMBER ;
            }
            $groupInfo['role'] = $userGroup['role'];
            $groupInfo['msg_setting'] = $userGroup['msg_setting'];
            $groupInfo['nickname_in_group'] = $userGroup['nickname_in_group'];
            $groupInfo['group_rename'] = $userGroup['group_rename'];

            return    $groupInfo;
           }catch(\Throwable $t){
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }

    /**
     * 编辑群
    */
    public function editGroup($param,$userInfo){
        try{
            #非本群成员无法修改
            $userGroup = UserGroupModel::create()->get(['group_id'=>$param['extra']['group_id'],'user_id'=>$userInfo['id']]);
            if(!$userGroup){
                return  ['code'=>ReponseCodeService::CODE_NOT_GROUP_MEMBER];
            }

            $updateInfo = array();
            if(isset($param['extra']['cover'])&&!empty($param['extra']['cover'])){
                $updateInfo['cover'] = $param['extra']['cover'];
            }

            if(isset($param['extra']['group_name'])&&!empty($param['extra']['group_name'])){
                $updateInfo['group_name'] = $param['extra']['group_name'];
            }


            #普通成员无法开启邀请
            if(isset($param['extra']['invite_mode'])&&!empty($param['extra']['invite_mode'])){
                $updateInfo['invite_mode'] = $param['extra']['invite_mode'];
                if($userGroup['role']==UserGroupModel::ROLE_TYPE_MEMBER){

                    return  ['code'=>ReponseCodeService::CODE_FAILE];
                }
            }
            #普通成员无法禁言
            if(isset($param['extra']['banned_to_post'])&&!empty($param['extra']['banned_to_post'])){
                $updateInfo['banned_to_post'] = $param['extra']['banned_to_post'];
                if($userGroup['role']==UserGroupModel::ROLE_TYPE_MEMBER){
                    return  ['code'=>ReponseCodeService::CODE_FAILE];
                }
            }
            #普通成员无法修改公告
            if(isset($param['extra']['notice'])&&!empty($param['extra']['notice'])){
                $updateInfo['notice'] = $param['extra']['notice'];
                if($userGroup['role']==UserGroupModel::ROLE_TYPE_MEMBER){
                    return  ['code'=>ReponseCodeService::CODE_FAILE];
                }
            }

            #非群主无法修改群主
            if(isset($param['extra']['app_user_id'])&&!empty($param['extra']['app_user_id'])){
                if($userGroup['role']!=UserGroupModel::ROLE_TYPE_CREATER){
                    return  ['code'=>ReponseCodeService::CODE_FAILE];
                }
                #成员不存在无法修改
                $newOwnerUserInfo = UserModel::create()->get(['app_user_id'=>$param['extra']['app_user_id'],'app_id'=>$userInfo['app_id']]);
                if(empty($newOwnerUserInfo)){
                    return  ['code'=>ReponseCodeService::CODE_FAILE];
                }
                #非本群成员无法修改
                if(!UserGroupModel::create()->get(['user_id'=>$newOwnerUserInfo['id'],'group_id'=>$param['extra']['group_id']])){
                    return  ['code'=>ReponseCodeService::CODE_FAILE];
                }
                $groupLogic = new GroupLogic();
                $ret = $groupLogic->changgeGroupOwner($param['extra']['group_id'],$userInfo['id'],'');
                if($ret!==ReponseCodeService::CODE_OK){
                    return  ['code'=>$ret];
                }
            }

            if(count($updateInfo)<=0){
                return  ['code'=>ReponseCodeService::CODE_EMPTY];
            }

            $updateInfo['updated_at'] = HelpService::msectimeToStr(HelpService::msectime());
            $updateInfo['version']  = HelpService::createVersion();
            #修改群信息
            if(GroupModel::create()->update($updateInfo,['id'=>$param['extra']['group_id']])){
                #增加系统消息
                $extra = $param['extra'];
                $extra['version'] =  $updateInfo['version'];

                $sysData['user_id'] = 0;
                $sysData['to_id'] = $param['extra']['group_id'];
                $sysData['sub_type'] = MsgModel::SUB_TYPE_GOUP_SYS_MSG;
                $sysData['app_id'] = $userInfo['app_id'];
                $sysData['msg'] = '';
                $sysData['extra'] = json_encode($extra);
                $sysData['nonce'] = HelpService::msectime().HelpService::createNonce(6);
                $sysData['type'] = PrivateMsgService::MSG_TYPE_GROUP_CHANGE;
                $sysData['created_at'] = HelpService::msectimeToStr(HelpService::msectime());
                $sysData['updated_at'] = HelpService::msectimeToStr(HelpService::msectime());
                $msgId =  MsgModel::create()->data($sysData)->save();
                return    ['code'=>ReponseCodeService::CODE_OK,'msg_id'=>$msgId];
            }
            return  ['code'=>ReponseCodeService::CODE_FAILE];

          }catch(\Throwable $t){
            return  ['code'=>ReponseCodeService::CODE_SERVICE_UNAVAILABLE];
        }
    }


    /**邀请群成员入群
     * @param $param
     * @param $userInfo
     */
    public function inviteMember($param,$userInfo){
        $appUserIdArr = explode(',',$param['extra']['app_user_ids']);
        $groupLogic = new GroupLogic();

        #判断是否本群成员，不是群成员无法邀请
        try{
            $userGroup = UserGroupModel::create()->get(['user_id'=>$userInfo['id'],'status'=>UserGroupModel::STATUS_NORMAL]);
             }catch(\Throwable $t){
            $messageArr = array(
                'code'=>ReponseCodeService::CODE_SERVICE_UNAVAILABLE,
                'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_SERVICE_UNAVAILABLE],
                'data'=>json_encode(array(),JSON_FORCE_OBJECT),
                'action'=>'inviteJoinGroup',
                'nonce'=>$param['nonce'],
                'time'=>HelpService::msectime(),
                'user_id'=>$userInfo['id'],
            );
            return $messageArr;
        }

        if(empty($userGroup)){
            $messageArr = array(
                'code'=>ReponseCodeService::CODE_NOT_GROUP_MEMBER,
                'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_NOT_GROUP_MEMBER],
                'data'=>json_encode(array(),JSON_FORCE_OBJECT),
                'action'=>'inviteJoinGroup',
                'nonce'=>$param['nonce'],
                'time'=>HelpService::msectime(),
                'user_id'=>$param['userInfo']['id'],
            );
            return $messageArr;
        }

        $appId = $userInfo['app_id'];
        $groupId = $param['extra']['group_id'];
        $groupRet = $groupLogic->invite($appId, $groupId,$appUserIdArr);

        if($groupRet['code']!=ReponseCodeService::CODE_SERVICE_UNAVAILABLE){
            if(!empty($groupRet['sucessArr'])){
                $memberWhere['user_groups.app_user_id'] = [$groupRet['sucessArr'],'in'];
                $memberList= $groupLogic->groupMemberList( $userInfo['app_id'],$groupId,1,1000,'',$memberWhere);
                $inviter['nickname'] = $userInfo['nickname'];
                $inviter['app_user_id'] = $userInfo['app_user_id'];
                $extra['inviter'] = $inviter;
                $param['extra']['group_id'] = $groupId;
                $extra['member_list'] = $memberList['list'];
                $extra['group_info'] = $this->groupDetail($param,$userInfo);

                $sysData['app_id'] = $userInfo['app_id'];
                $sysData['to_id'] =  $groupId;
                $sysData['user_id'] = 0;
                $sysData['msg'] = '';
                $sysData['extra'] = json_encode($extra);
                $sysData['nonce'] = HelpService::msectime().HelpService::createNonce(6);
                $sysData['type'] = PrivateMsgService::MSG_TYPE_GROUP_INVITE;
                $sysData['sub_type'] = MsgModel::SUB_TYPE_GOUP_SYS_MSG;
                $sysData['created_at'] = HelpService::msectimeToStr(HelpService::msectime());
                $sysData['updated_at'] = HelpService::msectimeToStr(HelpService::msectime());
                $msgId = MsgModel::create()->data($sysData)->save();
                $data['extra']['msg_id'] =  $msgId;
            }else{
                $data['extra']['msg_id'] =  null;
            }


            $data['extra']['ret'] =  $groupRet['ret'];
            $messageArr = array(
                'code'=>ReponseCodeService::CODE_OK,
                'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_OK],
                'data'=>json_encode($data),
                'action'=>'inviteJoinGroup',
                'nonce'=>$param['nonce'],
                'time'=>HelpService::msectime(),
                'user_id'=>$param['userInfo']['id'],
            );
            return $messageArr;
        }

        $messageArr = array(
            'code'=>ReponseCodeService::CODE_SERVICE_UNAVAILABLE,
            'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_NOT_GROUP_MEMBER],
            'data'=>json_encode(array(),JSON_FORCE_OBJECT),
            'action'=>'inviteJoinGroup',
            'nonce'=>$param['nonce'],
            'time'=>HelpService::msectime(),
            'user_id'=>$param['userInfo']['id'],
        );
        return $messageArr;
    }

    /**移除群成员
     * @param $param
     */
    public function removeMember($param){
        $userInfo = $param['userInfo'];
        $groupId = $param['extra']['group_id'];

        $messageArr = array(
            'data'=>json_encode(array(),JSON_FORCE_OBJECT),
            'action'=>'removeMember',
            'nonce'=>$param['nonce'],
            'time'=>HelpService::msectime(),
            'user_id'=>$userInfo['id'],
        );
        try{
            #校验本人是否是管理员
            $userGroupInfo = UserGroupModel::create()->get(['app_user_id'=>$userInfo['app_user_id'],'group_id'=>$groupId]);
            if( $userGroupInfo['role']==UserGroupModel::ROLE_TYPE_MEMBER){
                $messageArr['code'] = ReponseCodeService::CODE_USER_NOT_AUTH;
                $messageArr['msg'] = ReponseCodeService::$phrases[ReponseCodeService::CODE_USER_NOT_AUTH];
                return  $messageArr;
            }

            $userGroupModel = new UserGroupModel();

            //开启事务
            DbManager::getInstance()->startTransaction();
            $appUserIdArr = explode(',',$param['extra']['app_user_ids']);
            $sucessArr = array();
            foreach ($appUserIdArr as $appUserId){
                $userGroupModel->update(['status'=>UserGroupModel::STATUS_DEL,'updated_at'=>HelpService::msectimeToStr(HelpService::msectime())],['app_user_id'=>$appUserId,'group_id'=>$groupId]);
              if($userGroupModel->lastQueryResult()->getAffectedRows() ){
                  echo '状态修改成功';
                   $sucessArr[] = $appUserId;
               }
            }

            #修改群人数
            $memberCount = UserGroupModel::create()->where(['status'=>UserGroupModel::STATUS_NORMAL,'group_id'=>$groupId])->count();
            GroupModel::create()->update(['member_count'=>$memberCount,'updated_at'=>HelpService::msectimeToStr(HelpService::msectime())],['id'=>$groupId]);
            #系统消息

            $extra['admin']['nickname'] = $userInfo['nickname'];
            $extra['admin']['app_user_id'] = $userInfo['app_user_id'];
            $groupLogic = new GroupLogic();
            $memberWhere['user_groups.app_user_id'] = [$sucessArr,'in'];
            $updatedAt = HelpService::msectime()-1000*1000;
            $extra['group_id'] = $groupId;
            $data['extra']['msg_id'] = null;
            if(!empty($sucessArr)){
                $memberList= $groupLogic->groupMemberList( $userInfo['app_id'],$groupId,1,1000,$updatedAt,$memberWhere);
                $extra['removed_member_list'] = $memberList['list'];

            }else{
                $extra['removed_member_list'] = null;
            }
            $sysData['user_id'] = 0;
            $sysData['to_id'] = $groupId;
            $sysData['sub_type'] = MsgModel::SUB_TYPE_GOUP_SYS_MSG;
            $sysData['app_id'] = $userInfo['app_id'];
            $sysData['msg'] = '';
            $sysData['extra'] = json_encode($extra);
            $sysData['nonce'] = HelpService::msectime().HelpService::createNonce(6);
            $sysData['type'] = PrivateMsgService::MSG_TYPE_GROUP_REMOVE;
            $sysData['created_at'] = HelpService::msectimeToStr(HelpService::msectime());
            $sysData['updated_at'] = HelpService::msectimeToStr(HelpService::msectime());
            $msgId = MsgModel::create()->data($sysData)->save();
            $data['extra']['msg_id'] = $msgId;
            $messageArr['data'] =  json_encode($data,JSON_FORCE_OBJECT);
        } catch(\Throwable  $e){
            echo $e->getMessage();
            //回滚事务
            DbManager::getInstance()->rollback();
            $messageArr['code'] = ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
            $messageArr['msg'] = ReponseCodeService::$phrases[ReponseCodeService::CODE_SERVICE_UNAVAILABLE];
            return $messageArr;
        } finally {
            //提交事务
            DbManager::getInstance()->commit();
        }

        $messageArr['code'] = ReponseCodeService::CODE_OK;
        $messageArr['msg'] = ReponseCodeService::$phrases[ReponseCodeService::CODE_OK];
        return   $messageArr;
    }

    /**
     * 获取群成员信息
     */
    public function groupMemberList($param){
        $userInfo = $param['userInfo'];
        $groupId = $param['extra']['group_id'];
        try{
            #判断是否在群
            if(!UserGroupModel::create()->get(['group_id'=>$groupId,'user_id'=>$userInfo['id'],'status'=>UserGroupModel::STATUS_NORMAL])){
                $messageArr = array(
                    'code'=>ReponseCodeService::CODE_NOT_GROUP_MEMBER,
                    'data'=>json_encode(array(),JSON_FORCE_OBJECT),
                    'action'=>'groupMemberList',
                    'nonce'=>$param['nonce'],
                    'time'=>HelpService::msectime(),
                    'user_id'=>$userInfo['id'],
                    'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_NOT_GROUP_MEMBER]
                );
                return $messageArr;
            }
            $page = $param['extra']['page']; // 当前页码
            $limit = isset($param['extra']['limit'])?$param['extra']['limit']:1000000; // 每页多少条数据
            $updatedAt  = isset($param['extra']['updated_at'])?$param['extra']['updated_at']:'';
            $groupLogic = new GroupLogic();
            $ret = $groupLogic->groupMemberList($userInfo['app_id'],$groupId,$page,$limit,$updatedAt);
            if(!is_array($ret)){
                $messageArr = array(
                    'code'=>ReponseCodeService:: CODE_SERVICE_UNAVAILABLE,
                    'data'=>json_encode(array(),JSON_FORCE_OBJECT),
                    'action'=>'groupMemberList',
                    'nonce'=>$param['nonce'],
                    'time'=>HelpService::msectime(),
                    'user_id'=>$userInfo['id'],
                    'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_SERVICE_UNAVAILABLE]
                );
                return $messageArr;
            }
            $data['extra']  = $ret;
            $messageArr = array(
                'code'=>ReponseCodeService::CODE_OK,
                'data'=>json_encode($data),
                'action'=>'groupMemberList',
                'nonce'=>$param['nonce'],
                'time'=>HelpService::msectime(),
                'user_id'=>$userInfo['id'],
                'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_OK]
            );

            return $messageArr;

        }catch(\Throwable $t){
            $messageArr = array(
                'code'=>ReponseCodeService:: CODE_SERVICE_UNAVAILABLE,
                'data'=>json_encode(array(),JSON_FORCE_OBJECT),
                'action'=>'groupMemberList',
                'nonce'=>$param['nonce'],
                'time'=>HelpService::msectime(),
                'user_id'=>$userInfo['id'],
                'msg'=>$t->getMessage()
            );
            return $messageArr;
        }

    }

    /**
     * 退出群聊
     */
    public function leaveGroup($param){
        $userInfo = $param['userInfo'];
        $groupId = $param['extra']['group_id'];
        $userGroupLogic = new UserGroupLogic();
        $ret = $userGroupLogic->leaveGroup($param['userInfo']['id'], $groupId);
        if($ret == ReponseCodeService::CODE_OK){
            #系统消息入库
            try{
                $extra = $param['extra'];
                $extra['app_user_id'] = $param['userInfo']['app_user_id'];
                $extra['nickname'] = $param['userInfo']['nickname'];

                $sysData['user_id'] = 0;
                $sysData['to_id'] = $groupId;
                $sysData['sub_type'] = MsgModel::SUB_TYPE_GOUP_SYS_MSG;
                $sysData['app_id'] = $userInfo['app_id'];
                $sysData['msg'] = '';
                $sysData['extra'] = json_encode($extra);
                $sysData['nonce'] = HelpService::msectime().HelpService::createNonce(6);
                $sysData['type'] = MsgModel::MSG_TYPE_GROUP_LEAVE;
                $sysData['created_at'] = HelpService::msectimeToStr(HelpService::msectime());
                $sysData['updated_at'] = HelpService::msectimeToStr(HelpService::msectime());
                #如果是群主，退出群类型
                if(UserGroupModel::create()->get(['user_id'=>$userInfo['id'],'group_id'=>$groupId,'role'=>UserGroupModel::ROLE_TYPE_CREATER])){
                    $sysData['type'] = MsgModel::MSG_TYPE_GROUP_DEL;
                }
                $msgId = MsgModel::create()->data($sysData)->save();
            }catch(\Throwable $t){
                $msgId = null;
            }
            $reponse['extra'] = $param['extra'];
            $reponse['extra']['msg_id'] = $msgId;
            $messageArr = array(
                'code'=>$ret,
                'msg'=>ReponseCodeService::$phrases[$ret],
                'data'=>json_encode( $reponse,JSON_FORCE_OBJECT),
                'action'=>'leaveGroup',
                'nonce'=>$param['nonce'],
                'time'=>HelpService::msectime(),
                'user_id'=>$userInfo['id'],
            );
            return  $messageArr;
        }
        $messageArr = array(
            'code'=>$ret,
            'msg'=>ReponseCodeService::$phrases[$ret],
            'data'=>json_encode(array(),JSON_FORCE_OBJECT),
            'action'=>'leaveGroup',
            'nonce'=>$param['nonce'],
            'time'=>HelpService::msectime(),
            'user_id'=>$userInfo['id'],
        );
        return  $messageArr;
    }

    /**
     * 我的群
     */
    public function myGroup($param){
        $userInfo = $param['userInfo'];
        $type = isset($param['extra']['type'])?$param['extra']['type']:0;
        $page = $param['extra']['page']; // 当前页码
        $limit = isset($param['extra']['limit'])?$param['extra']['limit']:1000000; // 每页多少条数据
        try{
            switch ($type){
                case UserGroupModel::ROLE_TYPE_MEMBER:#普通
                    $condition = ['user_groups.user_id'=>$userInfo['id'],'user_groups.role'=>$type];
                    break;
                case UserGroupModel::ROLE_TYPE_ADMIN:#管理的群
                    $condition = ['user_groups.user_id'=>$userInfo['id'],'user_groups.role'=>$type];
                    break;
                case UserGroupModel::ROLE_TYPE_CREATER:#创建的群
                    $condition = ['user_groups.user_id'=>$userInfo['id'],'user_groups.role'=>$type];
                    break;
                default:#全部群
                    $condition = ['user_groups.user_id'=>$userInfo['id']];
            }
            $fields = 'group_lists.group_name,group_lists.version,user_groups.updated_at,group_lists.notice,group_lists.member_count,group_lists.id,group_lists.service_user_id,
            group_lists.cover,user_groups.status,group_lists.notice,group_lists.banned_to_post,user_groups.app_user_id,user_groups.msg_setting,user_groups.created_at,user_groups.role,
            user_groups.top,user_groups.nickname_in_group,user_groups.group_rename';
            $condition['service_user_id'] = 0;
            $model = UserGroupModel::create()
                ->join('group_lists','user_groups.group_id=group_lists.id')
                ->field($fields)
                ->limit($limit * ($page - 1), $limit)->withTotalCount()
                ->order('group_lists.id','asc');
            $condition['user_groups.status'] = UserGroupModel::STATUS_NORMAL;
            $condition['group_lists.status'] =GroupModel::STATUS_NORMAL;
            if(isset($param['extra']['id'])&&!empty($param['extra']['id'])){
                $condition['group_lists.id'] = [HelpService::msectimeToStr($param['extra']['id']),'>'];
            }

            $list =$model->all($condition);
            $result = $model->lastQueryResult();
            $total = $result->getTotalCount();
            $totalPage = ceil($total/$limit);
            if(!empty($list)){
                foreach ($list as &$val){
                    $val['created_at'] = HelpService::strDateToMsectime($val['created_at']);
                    $val['updated_at'] = HelpService::strDateToMsectime($val['updated_at']);
                }
            }
            $data['extra']['list'] = $list;
            $data['extra']['limit']  = $limit;
            $data['extra']['page']  = $page;
            $data['extra']['total'] = $total;
            $data['extra']['total_page']  = $totalPage;
            $messageArr = array(
                'code'=>ReponseCodeService::CODE_OK,
                'msg'=>'sucess',
                'data'=>json_encode($data),
                'action'=>'myGroup',
                'nonce'=>$param['nonce'],
                'time'=>HelpService::msectime(),
                'user_id'=>$param['userInfo']['id'],
            );
            return $messageArr;
        }catch(\Throwable $t){
            echo $t->getMessage();
            $messageArr = array(
                'code'=>ReponseCodeService::CODE_SERVICE_UNAVAILABLE,
                'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_SERVICE_UNAVAILABLE],
                'data'=>json_encode(array(),JSON_FORCE_OBJECT),
                'action'=>'myGroup',
                'nonce'=>$param['nonce'],
                'time'=>HelpService::msectime(),
                'user_id'=>$param['userInfo']['id'],
            );
            return $messageArr;
        }
    }

    /**获取客服群
     * @param $param
     */
    public function getServiceGroup($param){
        $groupLogic = new GroupLogic();
        $group = $groupLogic->getServiceGroup($param['userInfo']['id'],$param['userInfo']['app_user_id'],$param['userInfo']['app_id']);
        if(is_object($group)){
            $data['extra']['group_id'] = $group['id'] ;
            $messageArr = array(
                'code'=>ReponseCodeService::CODE_OK,
                'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_OK],
                'data'=>json_encode($data),
                'action'=>'getServiceGroup',
                'nonce'=>$param['nonce'],
                'time'=>HelpService::msectime(),
                'user_id'=>$param['userInfo']['id'],
            );
        }else{
            $data['extra'] = $group ;
            $messageArr = array(
                'code'=>ReponseCodeService::CODE_SERVICE_UNAVAILABLE,
                'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_SERVICE_UNAVAILABLE],
                'data'=>json_encode($data),
                'action'=>'getServiceGroup',
                'nonce'=>$param['nonce'],
                'time'=>HelpService::msectime(),
                'user_id'=>$param['userInfo']['id'],
            );
        }
        return  $messageArr ;
    }

    /**创建群聊
     * @param $param
     * @return array
     */
    public function createGroup($param,$userInfo,$serviceUserId='0'){
        $appUserIdArr = explode(',',$param['extra']['app_user_ids']);
        $groupName = isset($param['extra']['group_name'])?$param['extra']['group_name']:'';
        $cover = isset($param['extra']['cover'])?$param['extra']['cover']:'';
        $groupLogic = new GroupLogic();
        $groupRet = $groupLogic->createGroup($param['userInfo']['id'],$appUserIdArr,$userInfo['app_id'], $groupName ,$cover,$serviceUserId);

        if($groupRet!=ReponseCodeService::CODE_SERVICE_UNAVAILABLE){
            echo '创建的群id'.$groupRet.PHP_EOL;
            $param['userInfo'] = $userInfo;
            $param['extra']['group_id'] = $groupRet;
            $param['extra']['page'] = 1;
            $param['extra']['limit'] = 1000000;
            $groupInfo['group_info'] = $this->groupDetail($param,$userInfo);
            $memberWhere['user_groups.app_user_id'] = [$appUserIdArr,'in'];
            $memberList= $groupLogic->groupMemberList( $userInfo['app_id'],$groupRet,1,1000,'', $memberWhere);

            $groupInfo['member_list'] = $memberList['list'];
            $data['extra'] = $groupInfo;
            $data['extra']['msg_id'] ='';

            $inviter = UserGroupModel::create()
                ->join('users','user_groups.app_user_id=users.app_user_id','left')
                ->field('user_groups.app_user_id,user_groups.version,user_groups.nickname_in_group,user_groups.status,user_groups.created_at,user_groups.updated_at,user_groups.role,users.app_user_id,users.nickname,users.head')
                ->get(['users.id'=>$userInfo['id']]);

            $inviter['created_at'] = HelpService::strDateToMsectime($inviter['created_at']);
            $inviter['updated_at'] = HelpService::strDateToMsectime($inviter['updated_at']);

            $data['extra']['inviter'] = $inviter;
            $extra['group_info'] =  $groupInfo['group_info'];
            $extra['member_list'] = $memberList['list'];
            $extra['inviter'] = $inviter;
            #系统消息入库
            try{
                $sysData['app_id'] = $userInfo['app_id'];
                $sysData['user_id'] = 0;
                $sysData['to_id'] = $groupRet;
                $sysData['msg'] = '';
                $sysData['extra'] = json_encode($extra);
                $sysData['nonce'] = HelpService::msectime().HelpService::createNonce(6);
                $sysData['type'] = MsgModel::MSG_TYPE_GROUP_INVITE;
                $sysData['sub_type'] = MsgModel::SUB_TYPE_GOUP_SYS_MSG;
                $sysData['created_at'] = HelpService::msectimeToStr(HelpService::msectime());
                $sysData['updated_at'] = HelpService::msectimeToStr(HelpService::msectime());
                $id = MsgModel::create()->data($sysData)->save();
                $data['extra']['msg_id'] = $id;
             }catch(\Throwable $t){
                echo $t->getMessage();
            }
            $messageArr = array(
                'code'=>ReponseCodeService::CODE_OK,
                'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_OK],
                'data'=>json_encode($data),
                'action'=>'createGroup',
                'nonce'=>$param['nonce'],
                'time'=>HelpService::msectime(),
                'user_id'=>$param['userInfo']['id'],
            );
            return $messageArr;
        }

        $messageArr = array(
            'code'=>$groupRet,
            'msg'=>ReponseCodeService::$phrases[$groupRet],
            'data'=>json_encode(array(),JSON_FORCE_OBJECT),
            'action'=>'createGroup',
            'nonce'=>$param['nonce'],
            'time'=>HelpService::msectime(),
            'user_id'=>$param['userInfo']['id'],
        );
        return $messageArr;
    }
}